<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  NDatePicker,
  NSelect,
  NSpace,
  type DataTableColumns
} from 'naive-ui'
import { h, ref, reactive, onMounted, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import { RecordType } from '@/router/utils'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '用户',
    key: 'userName',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '部门',
    key: 'deptName',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '出发时间',
    key: 'departureTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '预计返回时间',
    key: 'returnTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '出差天数',
    key: 'errandDay',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '出差地点',
    key: 'errandTripList',
    width: '10rem',
    align: useStore.isCenter,
    render: ({ errandTripList }) => renderTrips(errandTripList),
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '200rem'
        }
      }
    }
  },
  {
    title: '出差事由',
    key: 'reasons',
    width: '10rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '申请时间',
    key: 'submitTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '审批状态',
    key: 'fromStatus',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0504')
            handleDetail(e)
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'info',
          loading: exportLoading.value,
          quaternary: true,
          style: {
            display: e.fromStatusCode == 'A0605' ? 'inline-flex' : 'none'
          },
          onClick: () => handleExport(e)
        },
        {
          default: () => '导出'
        }
      )
    ]
  }
]

//日期选择器
const timeRange: any = ref(null)
function handleUpdateFormattedValue(e: string[]) {
  if (timeRange.value == null) {
    formData.time = null
  } else {
    formData.time = e.toString()
  }
}

//筛选条件
type formType = {
  time: any
  deptId: any
}
const formData = reactive<formType>({
  time: null, //指标
  deptId: null
})
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

//部门类型
const partList: any = ref([])
const getPartName = async () => {
  const [error, res] = await sendRequest({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error) return message.error(error.message)
  partList.value = res.data
}
getPartName()

//处理出差地点数据
const renderTrips = (val: any) => {
  const tmp: any = []
  val?.map((i: any) => {
    tmp.push([i.departureLocation + '至' + i.destination])
  })
  return tmp.toString()
}

//详情
const handleDetail = (val: any) => {
  router.push({
    path: '/OA/Onbusiness/MineApplicationDetail',
    query: {
      id: val.id
    }
  })
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'application',
    api: 'totalapplicationList',
    override: {
      params: {
        ...formData,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data?.totalCount
  const tmp: any = res.data
  tableData.value = tmp?.list
}

//导出
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.pdf'
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const exportAllLoading = ref(false)
async function handleExportAll() {
  exportAllLoading.value = true
  const [error, data, headers] = await sendRequest({
    module: 'application',
    api: 'applicationSomeExport',
    override: {
      params: {
        page: 1,
        limit: 9999999,
        ...formData
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, data, '全馆出差统计')
  exportAllLoading.value = false
}


//单个导出
const exportLoading = ref(false)
async function handleExport(val: any) {
  exportLoading.value = true
  const [error, data, headers] = await sendRequest({
    module: 'application',
    api: 'applicationExport',
    override: {
      params: {
        errandId: val?.id
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, data, '全馆出差统计')
  exportLoading.value = false
}
//当前月第一天
function getFirstDay() {
  let y: any = new Date().getFullYear(); //获取年份
  let m: any = new Date().getMonth() + 1; //获取月份
  let d: any = "01";
  m = m < 10 ? "0" + m : m; //月份补 0
  return [y, m, d].join("-");
}
//当前月最后一天
function getLastDay() {
  let y: any = new Date().getFullYear(); //获取年份
  let m: any = new Date().getMonth() + 1; //获取月份
  let d: any = new Date(y, m, 0).getDate(); //获取当月最后一日
  m = m < 10 ? "0" + m : m; //月份补 0
  d = d < 10 ? "0" + d : d; //日数补 0
  return [y, m, d].join("-");
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/Onbusiness/totalApplicationList') {
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)

onMounted(
  async () => {
    if (route.path == '/OA/Onbusiness/totalApplicationList') {
      timeRange.value = [getFirstDay(), getLastDay()]
      formData.time = [getFirstDay(), getLastDay()]
      queryTableData()
    }
  },
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline>
          <NFormItem label="出发时间:">
            <NDatePicker input-readonly placeholder="请选择日期范围" type="daterange" v-model:formatted-value="timeRange"
              @update-formatted-value="handleUpdateFormattedValue" clearable />
          </NFormItem>
          <NFormItem label="部门:">
            <NSelect :options="partList" v-model:value="formData.deptId" placeholder="请选择部门" clearable
              style="width: 200px"  filterable label-field="name" value-field="value" />
          </NFormItem>
          <NFormItem>
            <NButton type="primary" style="width: 78px; margin-right: 40rem" ghost @click="queryTableData(true)">
              查询
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton type="primary" style="width: 115px" @click="handleExportAll" ghost :loading="exportAllLoading">
            导出
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
